import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { tableConfig,header } from '../data/config'
import store from 'store'

const base               = url.base,
      getPOSMerchantList = request.getPOSMerchantList,
      getChannelAll      = request.getChannelAll,
      editPOSMerchant    = request.editPOSMerchant,
      deletePOSMerchant  = request.deletePOSMerchant;

let table,
    storeData

// 初始化表格
table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getPOSMerchantList,
  queryParams: function (params) {
    return $.extend({
      currentPage : params.pageNumber,
      pageSize    : params.pageSize},
      $('#searchForm').serializeObject())
  },
  columns: [
    {
      field: 'keyIndex',
      title: '密钥索引',
      valign: 'middle',
    }, {
      field: 'authsn',
      title: '校验序列号',
      valign: 'middle',
      width: '200px',
      class: 'word-break',
    }, {
      field: 'keySnVersion',
      title: '设备码版本',
      valign: 'middle'
    }, {
      field: 'mchName',
      title: '商户名称',
      valign: 'middle',
    }, {
      field: 'mchNo',
      title: '商户号',
      valign: 'middle',
    }, {
      field: 'channel',
      title: '渠道',
      valign: 'middle',
    }, {
      field: 'actionTag',
      title: '动作标记',
      valign: 'middle',
    }, {
      field: 'status',
      title: '状态',
      valign: 'middle',
      formatter: function (index, row) {
        return index == 'open'? '<div class="text-success">● 打开</div>' : '<div class="text-danger">● 关闭</div>'
      }
    }, {
      field: 'action',
      valign: 'middle',
      align: 'center',
      width: '200px',
      title: '操作',
      formatter: function(index, row) {
        return `<div class="btn-group">
                      <button type="button" class="btn btn-default btn-modify">修改</button>
                      <button type="button" data-status="${ row.status }" data-id="${ row.idStr }" class="btn btn-default btn-switch">${ row.status == 'open' ? '关闭' : '打开'}</button>  
                      <button type="button" data-id="${ row.idStr }" class="btn btn-default btn-delete">删除</button>                   
                </div>`
      }
    }]
}))

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data
})

// 初始化渠道
getChannel();

function getChannel() {

  $.ajax({
    headers: header,
    url: base + getChannelAll
  })
    .done(function(res) {
      console.log("初始化渠道 success")
      console.log(res)

      let channel = $('#channel'),
        html      = '<option value="">请选择</option>',
        i         = 0,
        data      = res.object,
        len       = data.length

      for (; i < len; i++) {
        html += `<option value="${ data[i].key }">${ data[i].name }</option>`
      }

      channel.html(html)

    })
    .fail(function(res) {
      console.log(res)

      layer.msg('渠道获取失败', {
        icon: 5
      })

      console.log("error")
    })
    .always(function(res) {

      console.log("complete")
    })

}

// 搜索
$('#search-btn').on('click', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage : 1,
    }, $('#searchForm').serializeObject())
  })
})

// 删除
$(document).on('click', '#table .btn-delete', (e) => {
  e.preventDefault()

  console.log('删除')

  let id = $(e.target).attr('data-id');

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">是否删除？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '删除'
      }
    },
    callback: (result) => {

      if(!result){
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        headers: header,
        url : base + deletePOSMerchant,
        type: 'POST',
        data: {
          id: id
        }
      })
        .done(function (res) {
          console.log(res)

          if( res.code == 0 ){

            layer.msg('删除成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          }else {
            layer.msg('删除失败', {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('删除失败', {
            icon: 5
          })

        })
        .always(function(res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})


// 开关
$(document).on('click', '#table .btn-switch', (e) => {
  e.preventDefault()

  console.log('开关')

  let id     = $(e.target).attr('data-id'),
      status = $(e.target).attr('data-status'),
      sw     = status == 'open' ? 'close' : 'open',
      tit    = status == 'open' ? '关闭' : '打开',
      data   = {id: id,
               status: sw};

  console.log(JSON.stringify(data))
  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">是否 ${ tit } ？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: tit
      }
    },
    callback: (result) => {

      if(!result){
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        headers: header,
        url : base + editPOSMerchant,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data)
      })
        .done(function (res) {
          console.log(res)

          if( res.code == 0 ){

            layer.msg('操作成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          }else {
            layer.msg('操作失败', {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('操作失败', {
            icon: 5
          })

        })
        .always(function(res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
})

// 修改
$(document).on('click', '#table .btn-modify', (e) => {
  store.set('storeData', storeData)
  window.location = './modify.html'
})